package routers

import (
	"gin/middleware/cors"
	"gin/middleware/jwt"
	"gin/pkg/e"
	"gin/pkg/setting"
	v1 "gin/routers/api/v1"

	"github.com/gin-gonic/gin"
)

func InitRouter() *gin.Engine {
	r := gin.New()
	r.Use(gin.Logger())
	r.Use(cors.CorsHandler())
	r.Use(gin.Recovery())
	gin.SetMode(setting.RunMode)
	var authMiddleWare = jwt.GinJWTMiddlewareInit(&jwt.AllUserAuthorizator{})
	r.POST("/login", authMiddleWare.LoginHandler)
	//404 handler
	r.NoMethod(authMiddleWare.MiddlewareFunc(), func(context *gin.Context) {
		code := e.PAGE_NOT_FOUND
		context.JSON(e.PAGE_NOT_FOUND, gin.H{
			"code":    code,
			"message": e.GetMsg(code),
		})
	})
	auth := r.Group("/auth")
	{
		// Refresh time can be longer than token timeout
		auth.GET("reflesh_token", authMiddleWare.RefreshHandler)
	}

	api := r.Group("/user")
	api.Use(authMiddleWare.MiddlewareFunc())
	{
		api.GET("/info", v1.GetUserInfo)
		api.POST("/logout", v1.Logout)
	}
	return r
}
